<?php

class MTask extends MY_Model
{

    const STATE_NOT_ACCEPT = 0;
    const STATE_ACCEPTED = 1;

    //排序方式
    const ORDER_ID_DESC = 1;
    const ORDER_ID_ASC = 2;
    const ORDER_TASKOPERATE_NOTDEFINE_DESC = 3;
    const ORDER_TASKOPERATE_NOTDEFINE_ASC = 4;

    //是否加急
    const IS_URGENT_FALSE = 0;
    const IS_URGENT_TRUE = 1;
    protected $table = 'task';
    private $filter = array();
    public $has_accept ;

    function __construct()
    {
        parent::__construct();
    }

    public static function getState($state = NULL)
    {
        $define = array(self::STATE_ACCEPTED => '<span class="label label-success">可用</span>', self::STATE_NOT_ACCEPT => '<span class="label label-danger">禁用</span>',);
        if ($state === NULL) {
            return $define;
        } else {
            return key_exists($state, $define) ? $define[$state] : '';
        }
    }

    public static function getUrgent($is_urgent = NULL)
    {
        $define = array(self::IS_URGENT_FALSE => '<span class="label label-primary">否</span>', self::IS_URGENT_TRUE => '<span class="label label-danger">是</span>');
        if ($is_urgent === NULL) {
            return $define;
        } else {
            return key_exists($is_urgent, $define) ? $define[$is_urgent] : '';
        }
    }

    public static function getOrderType($orderType = NULL)
    {
        $define = array(
            self::ORDER_ID_DESC => 'ID倒序',
            self::ORDER_ID_ASC => 'ID升序',
            self::ORDER_TASKOPERATE_NOTDEFINE_DESC => '未审核数倒序',
            self::ORDER_TASKOPERATE_NOTDEFINE_ASC => '未审核数升序'

        );
        if ($orderType === NULL) {
            return $define;
        } else {
            return key_exists($orderType, $define) ? $define[$orderType] : '';
        }
    }


    public function getList($limit, $sort = false)
    {
        $has_accept = filterValue('has_accept');
        $this->db->select('t.*,an.apply_sale_num,an.apply_comment_num,an.finish_sale_num,an.finish_comment_num');
        $this->db->distinct();
        $this->db->from($this->table . ' as t');
        $this->db->join('task_apply_num an', 't.id = an.task_id AND an.operator_id = '.$this->_user->id, 'LEFT');

//        if (!in_array($this->_user->role_id,[2,4])){
//            $this->db->where('t.status',1);
//        }

        if ($this->_user->role_id == 2 || $this->_user->role_id == 4) { //2：账户组长；4：组员
            $this->db->where('t.group_id', (int)$this->_user->group_id);
        }

        if ($has_accept != ''){
            if ($has_accept){
                $this->db->where('(an.apply_sale_num > 0 or an.apply_comment_num > 0)');
            }else{
                $this->db->where('an.apply_sale_num is null');
            }
        }
        $this->formfilter->doFilter();
        $this->db->limit($limit['limit'], $limit['offset']);
        $this->db->order_by('t.id', 'desc');
        $query = $this->db->get();
        return $query->result();
    }


    public function getCount() {
        $has_accept = filterValue('has_accept');
        $this->db->select('count(distinct t.id) as num');
        $this->db->from($this->table . ' as t');
        $this->db->join('task_apply_num an', 't.id = an.task_id AND an.operator_id = '.$this->_user->id, 'LEFT');

        if ($this->_user->role_id == 2 || $this->_user->role_id == 4) { //2：账户组长；4：组员
            $this->db->where('t.group_id', (int)$this->_user->group_id);
        }
        if ($has_accept != ''){
            if ($has_accept){
                $this->db->where('(an.apply_sale_num > 0 or an.apply_comment_num > 0)');
            }else{
                $this->db->where('an.apply_sale_num is null');
            }
        }
        $this->formfilter->doFilter();
        $tmp = $this->db->get()->result();
        return (int)$tmp[0]->num;
    }

    public function getById($id)
    {
        $query = $this->db->where('id', $id)->get($this->table);
        return $query->row();
    }

    /**
     * @param array
     * @return object
     * excel 表格导出查询数据
     */
    public function exportList($where)
    {
        $this->db->select("t.*,s.name as shop_name,an.apply_sale_num,an.apply_comment_num,an.finish_comment_num,a1.name as creator_name,a2.name as task_contact_name,g.name as group_name");
        $this->db->from($this->table . ' t');
        $this->db->join('shops s', 't.shop_id = s.id', 'LEFT');
        $this->db->join('admins a1', 't.creator_id = a1.id', 'LEFT');
        $this->db->join('admins a2', 't.task_contact_id = a2.id', 'LEFT');
        $this->db->join('admin_group g', 't.group_id = g.id', 'LEFT');
        if (in_array($this->_user->role_id,[2,3,4,5])){
            $this->db->join('task_apply_num an', 't.id = an.task_id AND an.operator_id = '.$this->_user->id,'INNER');
        }else{
            $this->db->join('task_apply_num an', 't.id = an.task_id AND an.operator_id = '.$this->_user->id,'LEFT');
        }

        if ($begintime = $where['task_create_time_begin']) {
            $this->db->where(array('t.create_time >= ' => strtotime($begintime . ' 00:00:00')));
        }

        if ($endtime = $where['task_create_time_end']) {
            $this->db->where(array('t.create_time <= ' => strtotime($endtime . ' 23:59:59')));
        }

        if ($where['product_name']) {
            $this->db->where('t.product_name like' . ' %' . $where['product_name'] . '%');
        }
        if ($where['asin']) {
            $this->db->where('t.asin', $where['asin']);
        }
        if ($where['id']) {
            $this->db->where('t.id', $where['id']);
        }
        if ($where['shop_id']) {
            $this->db->where('t.shop_id', $where['shop_id']);
        }
        if ($where['group_id']) {
            $this->db->where('t.group_id', $where['group_id']);
        }
        if ($where['task_contact_id']) {
            $this->db->where('t.task_contact_id', $where['task_contact_id']);
        }
        if ($where['status']) {
            $this->db->where('t.status', $where['status']);
        }
        if ($where['is_urgent']) {
            $this->db->where('t.is_urgent', $where['is_urgent']);
        }
        if ($where['country']) {
            $this->db->where('t.country', $where['country']);
        }
        if ($where['has_accept'] != ''){
            if ($where['has_accept']){
                $this->db->where('(an.apply_sale_num > 0 or an.apply_comment_num > 0)');
            }else{
                $this->db->where('an.apply_sale_num is null');
            }
        }
        if ($this->_user->role_id == 2 || $this->_user->role_id == 4) {   //测评组的人，只能看到自己
            $this->db->where('t.group_id', $this->_user->group_id);
        }

        $this->db->order_by('t.create_time','desc');

        $result = $this->db->get()->result();

        foreach ($result as $k => $v) {
            $v->shop_id = $v->shop_name;
            $v->creator_id = $v->creator_name;
            $v->task_contact_id = $v->task_contact_name;
            $v->group_id = $v->group_name;
            $v->country = IOSS_StaticConfig::getCountryInfo($v->country);
            $v->is_urgent = $v->is_urgent ? '是' : '否';
            $v->create_time = date('Y-m-d H:i:s', $v->create_time);
        }
        return $result;
    }

    public function updateCepingCount($task_id)
    {
        $this->db->select('id,ceping_type');
        $this->db->from('task_operate');
        $this->db->where('task_id', $task_id);
        $this->db->where('status <>', 4);
        $list = $this->db->get()->result();
        $sales = 0;
        $cepings = 0;
        foreach ($list as $v) {
            if ($v->ceping_type == 1) {
                $sales = $sales + 1;
            } elseif ($v->ceping_type == 2) {
                $cepings = $cepings + 1;
            }
        }
        $arr = [
            'id' => $task_id,
            'sale_finish_num' => $sales,
            'comment_finish_num' => $cepings,
            'update_time' => time()
        ];
        $update = (object)$arr;
        $result = $this->update($update);
        return $result;
    }

    public function updateCepingRecordsCount($task_id)
    {
        $this->db->select('id,ceping_type');
        $this->db->from('task_records');
        $this->db->where('task_id', $task_id);
        $list = $this->db->get()->result();
        $sales = 0;
        $cepings = 0;
        foreach ($list as $v) {
            if ($v->ceping_type == 1) {
                $sales = $sales + 1;
            } elseif ($v->ceping_type == 2) {
                $cepings = $cepings + 1;
            }
        }
        $arr = [
            'id' => $task_id,
            'sale_finish_num' => $sales,
            'comment_finish_num' => $cepings,
            'update_time' => time()
        ];
        $update = (object)$arr;
        $result = $this->update($update);
        return $result;
    }

    public function descTaskFinishNumber($ceping_type,$task_id){
        $task_info = $this->getOne(['id' => $task_id]);
        if ($ceping_type == 1){
            $task_info->sale_finish_num = $task_info->sale_finish_num - 1;
        }elseif ($ceping_type == 2){
            $task_info->comment_finish_num = $task_info->comment_finish_num - 1;
        }
        $result = $this->update($task_info);
        return $result;
    }

    public function getCountNum($begintime, $endtime, $line_type, $allGroups, $apply)
    {
        $this->db->select('*');
        $this->db->from('task');

        if ($apply == 'init') {
            $x = $this->get_weeks();
            $this->db->where('create_time >= ',strtotime($x[0] . '00:00:00'));
            $this->db->where('create_time <= ',strtotime($x[6] . '23:59:59'));
        } else {
            $x = $this::getDateFromRange($begintime, $endtime, $line_type);
            if ($begintime) {
                $this->db->where('create_time >= ',strtotime($begintime . ' 00:00:00'));
            }
            if ($endtime) {
                $this->db->where('create_time <= ',strtotime($endtime . ' 23:59:59'));
            }
        }
        if (count($allGroups) == 1) {
            $this->db->where('group_id', key($allGroups));
        }

        $list = $this->db->get()->result();
        $item = array();

        //更改日期格式timestamp
        if ($line_type == 2) {
            $format = 'Y-m';
        } else if ($line_type == 3){
            $format = 'Y-m-d';
        }else if ($line_type == 1){
            $format = 'Y';
        }else{
            $format = 'Y-m-d';
        }

        foreach ($list as $value) {
            $value->create_time = date($format, $value->create_time);
            $item[] = $value;
        };

        //根据组ID转化
        $y_s = array();
        foreach ($item as $i_k => $i_v) {
            foreach ($x as $v) {
                if ($i_v->create_time == $v) {
                    $y_s[$v][] = $i_v->group_id;
                } else {
                    $y_s[$v][] = '';
                }
            }
        }

        $new = array();
        foreach ($y_s as $k => $v) {
            $new[$k] = array_filter($v);
        }

        $final = array();
        $series = array();
        foreach ($allGroups as $g_k => $g_v) {
            foreach ($new as $n_k => $n_v) {
                $value_times = array_count_values($n_v);
                if (in_array($g_k, $n_v)) {
                    $final[$g_k][] = $value_times[$g_k];
                } else {
                    $final[$g_k][] = 0;
                }
            }
            $series[] = [
                'name' => $g_v,
                'type' => 'line',
                'smooth' => true,
                'data' => $final[$g_k]
            ];
        }
        return [
            'xAxis' => ['data' => $x],
            'series' => $series
        ];
    }

    public function getPieData($begintime, $endtime, $allGroups, $apply){

        $this->db->select('id,group_id,create_time');
        $this->db->from('task');
        if ($apply == 'init') {
            $x = $this->get_weeks();
            $this->db->where('create_time >= ',strtotime($x[0] . ' 00:00:00'));
            $this->db->where('create_time <= ',strtotime($x[6] . ' 00:00:00'));
        }else{
            if ($begintime) {
                $this->db->where('create_time >= ',strtotime($begintime . ' 00:00:00'));
            }
            if ($endtime) {
                $this->db->where('create_time <= ',strtotime($endtime . ' 23:59:59'));
            }
        }

        $list = $this->db->get()->result();
        $arr = array();
        foreach ($allGroups as $k => $v){
            $arr[$k] = [];
            $arr[$k]['name'] = $v;
            $arr[$k]['value'] = 0;
            foreach ($list as $value){

                if ($k == $value->group_id){
                    $arr[$k]['value'] += 1;
                }
            }
        }
        return $arr;
    }
}
